package com.xyzwps.paimon.katheryne.commons.dbmapper;

import com.xyzwps.paimon.katheryne.modules.user.UserAccount;
import io.helidon.dbclient.DbRow;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public final class RowMappers {

    private static final ConcurrentHashMap<Class<?>, Function<DbRow, ?>> mapper = new ConcurrentHashMap<>();


    public static <T> void register(Class<T> c, Function<DbRow, T> map) {
        mapper.put(Objects.requireNonNull(c), Objects.requireNonNull(map));
    }

    @SuppressWarnings("unchecked")
    public static <T> T to(DbRow row, Class<T> c) {
        var fn = mapper.get(Objects.requireNonNull(c));
        if (fn == null) {
            throw new RuntimeException("No such row mapper");
        }
        return (T) fn.apply(row);
    }

    static {
        register(UserAccount.class, new RecordMapper<>(UserAccount.class)::from);
    }
}
